


local PANEL = {}

function PANEL:Init()
	self.animIn = Derma_Anim('OpenAnim', self, self.OpenAnim)
	self.animOut = Derma_Anim('CloseAnim', self, self.CloseAnim)

	self.hangOpen = false

	self:SetTitle(' Rewired')
	self:ShowCloseButton(false)

	self.updateButton = vgui.Create('DButton' , self)
	self.updateButton:SetSize(self:GetWide(), 20)
	self.updateButton:SetPos(0,self:GetTall()-20)
	self.updateButton:SetText('Update')
	self.updateButton.DoClick = function(button)
		self:UpdateChips()
	end

	self.panelmenu = {}
	self.filemenu = {}
	self.foldermenu = {}

	self:AddRightClick(self.filemenu, 'New File' , function()
		Derma_StringRequest('New File in "' .. string.GetPathFromFilename(self.File.FileDir) .. '"', 'Create new file', '',
 		function(strTextOut)
			file.Write(string.GetPathFromFilename(self.File.FileDir) .. '/' .. string.Replace(strTextOut, ' ', '_') .. '.txt', '')
			self:UpdateChips()
		end)
	end)
	self:AddRightClick(self.filemenu, 'Rename to..' , function()
		Derma_StringRequest('Rename File "' .. self.File.Name .. '"', 'Rename file ' .. self.File.Name, self.File.Name,
 		function(strTextOut)
			-- Renaming starts in the garrysmod folder now, in comparison to other commands that start in the data folder.
			file.Rename('data/' .. self.File.FileDir, 'data/' .. string.GetPathFromFilename(self.File.FileDir) .. '/' .. string.Replace(strTextOut,' ','_') .. '.txt')
			self:UpdateChips()
		end)
	end)
	self:AddRightClick(self.filemenu, 'Delete' , function()
		if(file.Exists(self.File.FileDir)) then file.Delete(self.File.FileDir) end
		self:UpdateChips()
	end)
	self:AddRightClick(self.filemenu, 'Copy to..' , function()
		Derma_StringRequest('Copy File "' .. self.File.Name .. '"', 'Copy File to...' , self.File.Name,
 		function(strTextOut)
			file.Write(string.GetPathFromFilename(self.File.FileDir) .. '/' .. string.Replace(strTextOut, ' ', '_') .. '.txt', file.Read(self.File.FileDir))
			self:UpdateChips()
		end)
	end)
	self:AddRightClick(self.foldermenu, 'New File..' , function()
		Derma_StringRequest('New File in "' .. self.File.FileDir .. '"', 'Create new file', '',
 		function(strTextOut)
			file.Write(self.File.FileDir .. '/' .. string.Replace(strTextOut, ' ', '_') .. '.txt', '')
			self:UpdateChips()
		end)
	end)
	self:AddRightClick(self.panelmenu, 'New File..' , function()
		Derma_StringRequest('New File in "' .. self.File.FileDir .. '"', 'Create new file', '',
 		function(strTextOut)
			file.Write(self.File.FileDir .. '/' .. string.Replace(strTextOut, ' ', '_') .. '.txt', '')
			self:UpdateChips()
		end)
	end)

	function self:OnFileClick(Dir)
		--Override this.
	end
	function self:OnFolderClick(Dir)
		--Override this.
	end

	self:UpdateChips()
end

function PANEL:HangOpen(hang)
	self.hangOpen = hang
end

function PANEL:HangingOpen()
	return self.hangOpen
end

function PANEL:Open()
	RestoreCursorPosition()

	self.hangOpen = false

	if (self:IsVisible()) then return end

	CloseDermaMenus()

	self:MakePopup()
	self:SetVisible(true)
	self:SetKeyboardInputEnabled(false)
	self:SetMouseInputEnabled(true)

	self.animOut:Stop()
	self.animIn:Start(0.05)
end

function PANEL:Close(bSkipAnim)
	if (self.hangOpen) then
		self.hangOpen = false
		return
	end

	RememberCursorPosition()

	CloseDermaMenus()

	self:SetKeyboardInputEnabled(false)
	self:SetMouseInputEnabled(false)

	self.animIn:Stop()

	if (bSkipAnim) then
		self:SetAlpha(224)
		self:SetVisible(false)
	else
		self.animOut:Start(0.1)
	end
end

function PANEL:Think()
	self.animIn:Run()
	self.animOut:Run()
end

function PANEL:UpdateChips()
	if (self.chipTree != nil) then self.chipTree:Remove() end
	self.chipTree = vgui.Create('DTree', self)
	self.chipTree:SetPadding(5)

	PopulateChipTree(self.chipTree, 'Rewired/Chips')

	self.chipTree.DoClick = function(tree, node) 
		self.File = node
		node:SetExpanded(!node.m_bExpanded)
		if(node.IsFile) then self:OnFileClick() else self:OnFolderClick() end
		return true
	end 
	self.chipTree.DoRightClick = function(tree, node)
		self.File = node
		if(node.IsFile) then self:OpenMenu(self.filemenu) else self:OpenMenu(self.foldermenu) end
		return true
	end 
	self.DoRightClick = function(self)
		self.File.FileDir = self.startfolder
		self:OpenMenu(self.panelmenu)
		return true
	end 

	self:PerformLayout()
end

function PANEL:PerformLayout()
	local wide = ScrW()/3 - 50
	local tall = ScrH() - 50

	self:SetSize(wide, tall)
	self:SetPos(25, 25)

	self.chipTree:SetPos(4, 4 + 24)
	self.chipTree:SetSize(wide - 8, tall/2 - 24 - 8)

	self.updateButton:SetPos(4, tall/2)
	self.updateButton:SetSize(wide - 8, 20)
end

function PANEL:OpenMenu(menu)
	if(!menu) then return end
	if(table.Count(menu)<1) then return end
	self.menu = vgui.Create("DMenu", self.chipTree)
	for k, v in pairs(menu) do
		self.menu:AddOption(k,v)
	end 
	self.menu:Open()
end

function PANEL:AddRightClick(menu, name, option)
	if(!menu) then menu = {} end
	if(menu[name]) then return end
	menu[name] = option
end

function PANEL:OpenAnim(anim, delta, data)
	if (anim.Started) then
		self:SetAlpha(0)
	end

	if (anim.Finished) then
		self:SetAlpha(224)
		return
	end

	self:SetAlpha(224 * delta)
end

function PANEL:CloseAnim(anim, delta, data)
	if (anim.Started) then
		self:SetAlpha(224)
	end

	if (anim.Finished) then
		self:SetAlpha(224)
		self:SetVisible(false)
		return
	end

	self:SetAlpha(224 - 224 * delta)
end

function PANEL:StartKeyFocus(pPanel)
	self.KeyFocus = pPanel
	self:SetKeyboardInputEnabled(true)
	self:HangOpen(true)
end

function PANEL:EndKeyFocus(pPanel)
	if (self.KeyFocus != pPanel) then return end
	self:SetKeyboardInputEnabled(false)
end

vgui.Register('GunMenu', PANEL, 'DFrame')



function PopulateChipTree(parent, dir)
	if (dir == nil) then return end

	parent:Clear()
	parent.ChildNodes = nil

	local folders = file.FindDir(dir .. '/*')
	for k, v in pairs(folders) do
		local folder = parent:AddNode(v)
		folder.FileDir = dir .. '/' .. v
		folder.IsFile = false
		folder.Name = v
		PopulateChipTree(folder, folder.FileDir)
	end

	local files = file.Find(dir .. '/*.txt')
	for k, v in pairs(files) do
		local name = string.Replace(string.Replace(v, '.txt', ''), '/', '')
		local file = parent:AddNode(name)
		file.FileDir = dir .. '/' .. v
		file.IsFile = true
		file.Name = name
		file.Icon:SetImage('vgui/spawnmenu/file')

		function file:InternalDoRightClick()
			self:GetRoot():SetSelectedItem(self)
			if (self:DoRightClick()) then return end
			if (self:GetRoot():DoRightClick(self)) then return end
		end
	end
end



local function CreateGunMenu()
	if (g_GunMenu) then
		g_GunMenu:Remove()
		g_GunMenu = nil
	end

	g_GunMenu = vgui.Create('GunMenu')
	g_GunMenu:SetVisible(false)
end
hook.Add('OnGamemodeLoaded', 'CreateGunMenu', CreateGunMenu)


function GM:OnSpawnMenuOpen()
	if (g_GunMenu) then g_GunMenu:Open() end
end

function GM:OnSpawnMenuClose()
	if (g_GunMenu) then g_GunMenu:Close() end
end


local function GunMenuKeyboardFocusOn(pnl)
	if (!ValidPanel(g_GunMenu)) then return end
	if (!pnl:HasParent(g_GunMenu)) then return end

	g_GunMenu:StartKeyFocus(pnl)
end
hook.Add('OnTextEntryGetFocus', 'GunMenuKeyboardFocusOn', GunMenuKeyboardFocusOn)


local function GunMenuKeyboardFocusOff(pnl)
	if (!ValidPanel(g_GunMenu)) then return end
	if (!pnl:HasParent(g_GunMenu)) then return end

	g_GunMenu:EndKeyFocus(pnl)
end
hook.Add('OnTextEntryLoseFocus', 'GunMenuKeyboardFocusOff', GunMenuKeyboardFocusOff)


local function GunMenuOpenGUIMousePressed()
	if (!ValidPanel(g_GunMenu)) then return end
	if (!g_GunMenu:IsVisible()) then return end

	return true
end
hook.Add('GUIMousePressed', 'GunMenuOpenGUIMousePressed', GunMenuOpenGUIMousePressed)


local function GunMenuOpenGUIMouseReleased()
	if (!ValidPanel(g_GunMenu)) then return end
	if (!g_GunMenu:IsVisible()) then return end

	g_GunMenu:Close()

	return true
end
hook.Add('GUIMouseReleased', 'GunMenuOpenGUIMouseReleased', GunMenuOpenGUIMouseReleased)
